package com.framework.mybatis.config;

import com.framework.common.utils.SpringContextUtil;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.Cache;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.util.DigestUtils;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author lihanbo
 * @date 2021/9/16 13:34
 */
@Slf4j
public class MybatisPlusRedisCache implements Cache {

    private RedissonClient redissonClient;
    private String id;

    /**
     * 手动获取bean
     */
    private void getRedissonClient() {
        if (redissonClient == null) {
            redissonClient = SpringContextUtil.getBean(RedissonClient.class);
        }
    }

    public MybatisPlusRedisCache(final String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        this.id = id;
    }

    @Override
    public String getId() {
        return this.id;
    }

    public String redisId() {
        return "mybatisCache:" + id;
    }

    @Override
    public void putObject(Object key, Object value) {
        this.getRedissonClient();
        try {
            //将key加密后存入
            if (value != null) {
                RMap<Object, Object> bucket = redissonClient.getMap(redisId());
                bucket.put(this.MD5Encrypt(key), value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object getObject(Object key) {
        this.getRedissonClient();
        try {
            if (key != null) {
                return redissonClient.getMap(redisId()).get(this.MD5Encrypt(key));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Object removeObject(Object key) {
        this.getRedissonClient();
        try {
            if (key != null) {
                redissonClient.getMap(redisId()).remove(this.MD5Encrypt(key));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void clear() {
        this.getRedissonClient();
        try {
            redissonClient.getMap(redisId()).delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getSize() {
        this.getRedissonClient();
        long size = redissonClient.getMap(redisId()).keySet().size();
        return (int) size;
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return Cache.super.getReadWriteLock();
    }

    /**
     * MD5加密存储key,以节约内存
     */
    private String MD5Encrypt(Object key) {
        return DigestUtils.md5DigestAsHex(key.toString().getBytes());
    }
}
